/**
 * [functionName description]
 * @param  {string}   value         [当前值]
 * @param  {array}    option        [map对象, value: 1234, name: 12345]
 * @param  {function} selectClick   [选择选项后的事件触发 function(name, value) {}]
 */
class select extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false,
      value: '',
      name: '',
      isValue: true,
      option: {}
    }

    this.openClick = this.openClick.bind(this);
    this.selectClick = this.selectClick.bind(this);
  }

  componentWillMount () {
    this.props.option.map((index)=>{
      if (index.value === this.props.value) {
        this.state.isValue = false;
        this.setState({name: index.name, value: index.value})
        return;
      }
    });
    this.state.isValue && this.setState({
      name: this.props.option[0].name,
      value: this.props.option[0].value
    });
  }

  openClick(E) {
    this.setState({
      open: !this.state.open
    })
  }

  selectClick(E) {
    const target = E.target;
    if (target.nodeName === "LI") {
      const name = target.innerHTML;
      const value = target.dataset.value;

      this.setState({
        name: name,
        value: value,
        open: !this.state.open
      });

      this.props.selectClick && typeof this.props.selectClick && this.props.selectClick(name, value);
    }
  }


  render() {
    return (
      <div  className={this.state.open ? "selectDown open" : "selectDown"}>
        <span data-value={this.state.value} className={this.props.disabled ? 'disabled' : ''} onClick={this.props.disabled ? '' : this.openClick}>{this.state.name}</span>
        <ul className={this.state.open ? 'nav-menu-vertical open' : 'nav-menu-vertical'} onClick={this.selectClick}>
          {
            this.props.option
            ? this.props.option.map((key, i)=>{
                  return(
                  <li key={i} data-value={key.value}>{key.name}</li>
                )
              })
            : ''
          }
        </ul>
      </div>
    )
  }
}

module.exports = select;
